<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="审批单号" prop="outStoId">
        <el-input
          v-model="queryParams.outStoId"
          placeholder="请输入审批单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="outStoState">
        <el-select
          v-model="queryParams.outStoState"
          placeholder="请选择审批状态"
          clearable
        >
          <el-option
            v-for="(state, index) in states"
            :key="state"
            :label="state"
            :value="index"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格展示 -->
    <el-table
      v-loading="loading"
      :data="outsto"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="申请编号"
        width="100"
        align="center"
        prop="stoId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="审批状态"
        align="center"
        prop="outStoState"
        :formatter="personStatusFormatter"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="出货仓库"
        align="center"
        prop="outStoWarehouse"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="审批负责人"
        align="center"
        prop="outStoActor"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip
            content="查看"
            placement="top"
            v-if="scope.row.outStoState == '1' || scope.row.outStoState == '2'"
          >
            <el-button
              type="text"
              icon="Search"
              @click="handleSearch(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="审批" placement="top" v-else>
            <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改审批表状态对话框 -->
    <el-dialog
      v-if="checkopen"
      :title="title"
      v-model="checkopen"
      width="800px"
      append-to-body
    >
      <el-form ref="jobRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批表编号" prop="outStoId">
              <el-input
                v-model="form.outStoId"
                aria-readonly="true"
                :disabled="form.outStoState != '0'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库仓库" prop="outStoWarehouse">
              <el-select
                v-model="form.outStoWarehouse"
                placeholder="请选择出库的仓库"
                :disabled="form.outStoState != '0'"
              >
                <el-option
                  v-for="dict in warehouse"
                  :key="dict.warehouseName"
                  :label="dict.warehouseName"
                  :value="dict.warehouseName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人" prop="outStoActor">
              <el-select
                v-model="form.outStoActor"
                placeholder="请选择审批人"
                :disabled="form.outStoState != '0'"
              >
                <el-option
                  v-for="dict in users"
                  :key="dict.userName"
                  :label="dict.userName"
                  :value="dict.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="form.saleOutinventory">
        <el-table-column label="审批商品信息" align="center">
          <el-table-column
            prop="productId"
            label="商品编号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="productName"
            label="商品名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="brand"
            label="商品品牌"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="salesDetNum"
            label="商品数量"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="note"
            label="备注"
            align="center"
          ></el-table-column>
        </el-table-column>
      </el-table>
      <template #footer v-if="form.outStoState == '0'">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">通过</el-button>
          <el-button type="primary" @click="submitFormNo">打回</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="outsto">
import {
  getData,
  getOutSto,
  listOutSto,
  updateOutSto,
} from "@/api/reserve/outsto";

// const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_job_group, sys_job_status } = proxy.useDict(
//   "sys_job_group",
//   "sys_job_status"
// );

const outsto = ref([]);
const states = ref(["待审批", "审批通过", "打回"]);
const warehouse = ref([]);
const users = ref([]);
const checkopen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openView = ref(false);
const openCron = ref(false);
const expression = ref("");

const data = reactive({
  form: {},
  rules: {
    outStoActor: [
      { required: true, message: "审批人不能为空", trigger: "change" },
      // ...其他验证规则...
    ],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    outStoId: undefined,
    outStoState: undefined,
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询定时任务列表 */
function getList() {
  loading.value = true;
  listOutSto(queryParams.value).then((response) => {
    outsto.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
    console.log(outsto);
  });
}

/** 取消按钮 */
function cancel() {
  checkopen.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm("jobRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.warehouseId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleUpdate(row) {
  reset();
  const stoId = row.stoId || ids.value;
  getOutSto(stoId).then((response) => {
    form.value = response.data;
    checkopen.value = true;
    title.value = "审批详情";
    getData(response.data.saleOutinventory[0].productId).then((response) => {
      users.value = response.data.users;
      warehouse.value = response.data.warehouse;
    });
  });
}

function handleSearch(row) {
  reset();
  const stoId = row.stoId || ids.value;
  getOutSto(stoId).then((response) => {
    form.value = response.data;
    checkopen.value = true;
    title.value = "审批详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["jobRef"].validate((valid) => {
    if (valid) {
      if (form.value.stoId !== undefined) {
        form.value.outStoState = 1;
        updateOutSto(form.value, users.value, warehouse.value).then(
          (response) => {
            open.value = false;
            proxy.$modal.msgSuccess("审核成功");
            checkopen.value = false;
            getList();
          }
        );
      }
    }
  });
}

function submitFormNo() {
  proxy.$refs["jobRef"].validate((valid) => {
    if (valid) {
      if (form.value.stoId !== undefined) {
        form.value.outStoState = "2";
        updateOutSto(form.value, users.value, warehouse.value).then(
          (response) => {
            proxy.$modal.msgSuccess("打回成功");
            open.value = false;
            checkopen.value = false;
            getList();
          }
        );
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const stoId = row.stoId || ids.value;
  proxy.$modal
    .confirm('是否确认删除销售订单为"' + stoId + '"的数据项?')
    .then(function () {
      return delOutsto(stoId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

//状态展示文字加工
function personStatusFormatter(row) {
  // 确保 orderStatus 是有效的索引
  if (row.outStoState !== undefined && row.outStoState < states.value.length) {
    return states.value[row.outStoState];
  }
  return ""; // 或者返回一个默认值
}

getList();

let timerId;

// 设置定时器，每隔10秒调用一次getList函数
timerId = setInterval(getList, 10000);

onBeforeUnmount(() => {
  // 清除定时器
  clearInterval(timerId);
});
</script>
